<template>
  <div>
    <el-form :inline="true" :model="searchForm" style="margin-bottom: 20px;">
      <el-form-item label="组织关键字">
        <el-input v-model="searchForm.keyword" placeholder="请输入组织关键字" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="orgs" style="width: 100%">
      <el-table-column prop="name" label="组织名称">
        <template #default="scope">
          <el-link type="primary" @click="goDetail(scope.row)">{{ scope.row.name }}</el-link>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const stuId = localStorage.getItem('loginId')
const orgs = ref([])
const searchForm = ref({
  keyword: ''
})

// 获取所有组织
const fetchAllOrgs = async () => {
  try {
    const res = await axios.get('http://localhost:8080/student/getAllOrgs')
    if (res.data && res.data.code === 200) {
      orgs.value = res.data.data || []
    } else {
      orgs.value = []
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '获取组织失败')
    }
  } catch (e) {
    ElMessage.error('获取组织失败')
  }
}

onMounted(fetchAllOrgs)

// 跳转到组织详情页面
const goDetail = (row) => {
  router.push({ name: 'StuOrgDetail', params: { orgId: row.orgId } })
}

// 搜索功能（根据组织名字搜索）
const handleSearch = async () => {
  if (searchForm.value.keyword) {
    try {
      const res = await axios.get(
        `http://localhost:8080/student/${stuId}/${searchForm.value.keyword}/getOrgByName`
      )
      if (res.data && (res.data.code === 200 || res.data.code === 201) && res.data.data) {
        // 这里后端返回的是单个对象，前端需要转为数组以适配表格
        orgs.value = [res.data.data]
      } else {
        orgs.value = []
        ElMessage.error(res.data && res.data.msg ? res.data.msg : '未找到相关组织')
      }
    } catch (e) {
      ElMessage.error('搜索失败')
    }
  } else {
    fetchAllOrgs()
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.value.keyword = ''
  fetchAllOrgs()
}
</script>